package com.xiaoma.myaudience.biz.view;

import java.lang.reflect.Field;
import java.util.Formatter;
import java.util.Locale;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.util.Logger;
import com.xiaoma.myaudience.util.NetUtils;
import com.xiaoma.myaudience.util.SystemUtils;

/**
 * A view containing controls for a MediaPlayer. Typically contains the
 * buttons like "Play/Pause", "Rewind", "Fast Forward" and a progress
 * slider. It takes care of synchronizing the controls with the state
 * of the MediaPlayer.
 * <p>
 * The way to use this class is to instantiate it programatically.
 * The MediaController will create a default set of controls
 * and put them in a window floating above your application. Specifically,
 * the controls will float above the view specified with setAnchorView().
 * The window will disappear if left idle for three seconds and reappear
 * when the user touches the anchor view.
 * <p>
 * Functions like show() and hide() have no effect when MediaController
 * is created in an xml layout.
 * 
 * MediaController will hide and
 * show the buttons according to these rules:
 * <ul>
 * <li> The "previous" and "next" buttons are hidden until setPrevNextListeners()
 *   has been called
 * <li> The "previous" and "next" buttons are visible but disabled if
 *   setPrevNextListeners() was called with null listeners
 * <li> The "rewind" and "fastforward" buttons are shown unless requested
 *   otherwise by using the MediaController(Context, boolean) constructor
 *   with the boolean set to false
 * </ul>
 */
public class MyMediaController extends MediaController {

    private MediaPlayerControl  mPlayer;
    private Context             mContext;
    private View                mAnchor;
    private View                mRoot;
    private WindowManager       mWindowManager;
    private Window              mWindow;
    private ViewGroup                mDecor;
    private ProgressBar         mProgress;
    private TextView            mEndTime, mCurrentTime;
    private boolean             mShowing;
    private boolean             mDragging;
    private static final int    sDefaultTimeout = 5000;
    private static final int    FADE_OUT = 1;
    private static final int    SHOW_PROGRESS = 2;
    private boolean             mUseFastForward;
    private boolean             mFromXml;
    private boolean             mListenersSet;
    private View.OnClickListener mNextListener, mPrevListener;
    StringBuilder               mFormatBuilder;
    Formatter                   mFormatter;
    private ImageButton         mPauseButton;
    private ImageButton         mFfwdButton;
    private ImageButton         mRewButton;
    private ImageButton         mNextButton;
    private ImageButton         mPrevButton;
    
	private ImageButton         mVolumeButton;  //按钮，用来显示或隐藏音量seekbar
	private VerticalSeekBar     mVolumeSeekBar; //调整音量的seekbar
	private AudioManager mAudioManager;
	private int maxVolume;
	private VerticalSeekBar mBrightSeekBar; //调整亮度的seekbar
	private ImageButton mBrightButton;      //按钮，用来显示或隐藏亮度seekbar
	private TextView mTime;                 //当前时间
	private TextView mBattery;              //当前电量
	private TextView mNetwork;              //当前网络类型
	private Button mEpisode;                //剧集按钮
	private LinearLayout mEpisodeList;      //剧集列表
	private BroadcastReceiver batteryLevelReceiver; 
	
	private final static String BRIGHT_TAG = "video_bright";

    public MyMediaController(Context context, AttributeSet attrs) {
        super(context, attrs);
        mRoot = this;
        mContext = context;
        mUseFastForward = true;
        mFromXml = true;
        initFloatingWindow();
    }

    @Override
    public void onFinishInflate() {
        if (mRoot != null)
            initControllerView(mRoot);
    }

    public MyMediaController(Context context, boolean useFastForward) {
        super(context);
        mContext = context;
        mUseFastForward = useFastForward;
        initFloatingWindow();
    }

    public MyMediaController(Context context) {
        super(context);
        mContext = context;
        mRoot = this;
        mUseFastForward = true;
        initFloatingWindow();
    }

    private void initFloatingWindow() {
        mWindowManager = (WindowManager)mContext.getSystemService("window");
   
        mDecor = new FrameLayout(mContext);
        mDecor.addView(this);
        mDecor.setOnTouchListener(mTouchListener);
        mDecor.setBackgroundResource(android.R.color.transparent);
        
        setFocusable(true);
        setFocusableInTouchMode(true);
        setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
        requestFocus();
    }

    private OnTouchListener mTouchListener = new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (mShowing) {
                    hide();
                }
            }
            return false;
        }
    };
	private HorizontalScrollView mEpisodeSrollView;
	private TextView mTitle;
	private String mTitleText;
	private int mVnumber;
    
    public void setMediaPlayer(MediaPlayerControl player) {
        mPlayer = player;
        updatePausePlay();
    }

    /**
     * Set the view that acts as the anchor for the control view.
     * This can for example be a VideoView, or your Activity's main view.
     * @param view The view to which to anchor the controller when it is visible.
     */
    public void setAnchorView(View view) {
        mAnchor = view;

        FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.FILL_PARENT
        );

        removeAllViews();
        View v = makeControllerView();
        addView(v, frameParams);
     
    }

    /**
     * Create the view that holds the widgets that control playback.
     * Derived classes can override this to create their own.
     * @return The controller view.
     * @hide This doesn't work as advertised
     */
    protected View makeControllerView() {
        LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mRoot = (ViewGroup) inflate.inflate(R.layout.media_controller, null);

        initControllerView(mRoot);
        
        return mRoot;
    }

    private void initControllerView(View v) {
        mPauseButton = (ImageButton) v.findViewById(R.id.pause);
        if (mPauseButton != null) {
        	mPauseButton.requestFocus();
            mPauseButton.setOnClickListener(mPauseListener);
        }

        mFfwdButton = (ImageButton) v.findViewById(R.id.ffwd);
        if (mFfwdButton != null) {
            mFfwdButton.setOnClickListener(mFfwdListener);
            if (!mFromXml) {
                mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
            }
        }

        mRewButton = (ImageButton) v.findViewById(R.id.rew);
        if (mRewButton != null) {
            mRewButton.setOnClickListener(mRewListener);
            if (!mFromXml) {
                mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
            }
        }

        // By default these are hidden. They will be enabled when setPrevNextListeners() is called 
        mNextButton = (ImageButton) v.findViewById(R.id.next);
        if (mNextButton != null && !mFromXml && !mListenersSet) {
            mNextButton.setVisibility(View.GONE);
        }
        mPrevButton = (ImageButton) v.findViewById(R.id.prev);
        if (mPrevButton != null && !mFromXml && !mListenersSet) {
            mPrevButton.setVisibility(View.GONE);
        }

        mProgress = (ProgressBar) v.findViewById(R.id.mediacontroller_progress);
        if (mProgress != null) {
            if (mProgress instanceof SeekBar) {
                SeekBar seeker = (SeekBar) mProgress;
                seeker.setOnSeekBarChangeListener(mSeekListener);
            }
            mProgress.setMax(1000);
        }

        mEndTime = (TextView) v.findViewById(R.id.time);
        mCurrentTime = (TextView) v.findViewById(R.id.time_current);
        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
        
        
    	mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    	maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    	
        mVolumeSeekBar = (VerticalSeekBar) v.findViewById(R.id.volume_seekbar);
        if(mVolumeSeekBar != null) {
        	mVolumeSeekBar.setMax(maxVolume);  
        	mVolumeSeekBar.setOnSeekBarChangeListener(mVolumeSeekListener);
        }
    	
        mVolumeButton = (ImageButton) v.findViewById(R.id.volume);
        if (mVolumeButton != null) {  	   	
        	mVolumeButton.setOnClickListener(mVolumnListener);
        }
        
        mBrightSeekBar = (VerticalSeekBar) v.findViewById(R.id.bright_seekbar);
        if(mBrightSeekBar != null) {
        	//mBrightSeekBar.set
        	mBrightSeekBar.setMax(255);  
        	mBrightSeekBar.setOnSeekBarChangeListener(mBrightSeekListener);
        }
    	
        mBrightButton = (ImageButton) v.findViewById(R.id.bright);
        if (mBrightButton != null) {  	   	
        	mBrightButton.setOnClickListener(mBrightListener);
        }
        
        setInitBright();
        
        mTitle = (TextView) v.findViewById(R.id.controller_video_title);
        if(mTitle != null) mTitle.setText(mTitleText+" "+getEpisodeText(mVnumber));
        
		mTime = (TextView) v.findViewById(R.id.controller_video_time);
		mBattery = (TextView) v.findViewById(R.id.controller_video_battery);
		mNetwork = (TextView) v.findViewById(R.id.controller_video_network);
		
		setBatteryLevel();
		
		mEpisode = (Button) v.findViewById(R.id.controller_video_episode_button);
		if(mEpisode != null) {
			if(mEpisodeCount <= 0) mEpisode.setVisibility(View.GONE);
			else {
				mEpisode.setVisibility(View.VISIBLE);
				mEpisode.setOnClickListener(mEpisodeListener);
			}
		}
		mEpisodeSrollView = (HorizontalScrollView) v.findViewById(R.id.controller_video_episode);
		if(mEpisodeSrollView != null) {
			mEpisodeSrollView.setOnTouchListener(mEpisodeTouchListener);
		}
		
		mEpisodeList = (LinearLayout) v.findViewById(R.id.controller_video_episode_list);
		if(mEpisodeList != null) {
			fillEpisodeList(mEpisodeCount);
			mEpisodeList.setOnTouchListener(mEpisodeTouchListener);
		}

        installPrevNextListeners();
    }
    
    /**
     * 触摸剧集列表或按钮时，保持显示
     */
    private OnTouchListener mEpisodeTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			show(sDefaultTimeout);
			return false;
		}
    	
    };
    
    /**
     * 设置视频的title和当前第几集
     * @param text
     * @param vnum
     */
    public void setVideoTitle(String text, int vnum) {
    	mTitleText = text;
    	mVnumber = vnum;
    }
    
    private int mEpisodeCount = 0; //总共集数
    
    /**
     * 设置总集数
     * @param num
     */
    public void setEpisodeCount(int num) {
    	mEpisodeCount = num;
    }
    
    /**
     * 填充剧集列表
     * @param num
     */
    private void fillEpisodeList(int num) {
    	Button b = null;
    	mEpisodeList.removeAllViews();
    	if(num <= 0) return;
    	for(int i=0; i<num; i++) {
    		b = new Button(mContext);
    		b.setText(getEpisodeText(i+1));
    		b.setTag(i+1);
    		b.setOnTouchListener(mEpisodeTouchListener);
    		b.setOnClickListener(mEpisodeListListener);
    		mEpisodeList.addView(b);
    	}
    }
    
    private String getEpisodeText(int index) {
    	return String.format("第%d集", index);
    }
    
    /**
     * 设置网络类型
     */
    private void setNetwork() {
    	if(NetUtils.isAvailable(mContext)) {
    		if(NetUtils.isWIFI(mContext)) {
    			mNetwork.setText("[WIFI]");
    		} else {
    			mNetwork.setText("[3G/2G]");
    		}
    	}
    }
    
    /**
     * 设置当前时间
     */
    private void setCurrentTime() {
    	mTime.setText(SystemUtils.getCurrentTime());
    }
    
	/**
     * 获得电量
     */
    private void setBatteryLevel() {
        batteryLevelReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                //context.unregisterReceiver(this);
                int rawlevel = intent.getIntExtra("level", -1);//获得当前电量
                int scale = intent.getIntExtra("scale", -1); //获得总电量
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                mBattery.setText(level + "%");
            }
        };
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        mContext.registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }
    
    public void unregisterBatteryReceiver() {
    	if(batteryLevelReceiver != null) mContext.unregisterReceiver(batteryLevelReceiver);
    }

    /**
     * Show the controller on screen. It will go away
     * automatically after 3 seconds of inactivity.
     */
    public void show() {
        show(sDefaultTimeout);
    }

    /**
     * Disable pause or seek buttons if the stream cannot be paused or seeked.
     * This requires the control interface to be a MediaPlayerControlExt
     */
    private void disableUnsupportedButtons() {
        try {
			Field mCanPause = mPlayer.getClass().getSuperclass().getDeclaredField("mCanPause");
			Field mCanSeekBack = mPlayer.getClass().getSuperclass().getDeclaredField("mCanSeekBack");
			Field mCanSeekForward = mPlayer.getClass().getSuperclass().getDeclaredField("mCanSeekForward");
			mCanPause.setAccessible(true);
			mCanSeekBack.setAccessible(true);
			mCanSeekForward.setAccessible(true);
			
            if (mPauseButton != null && !mCanPause.getBoolean(mPlayer)) {
                mPauseButton.setEnabled(false);
            }
            if (mRewButton != null && !mCanSeekBack.getBoolean(mPlayer)) {
                mRewButton.setEnabled(false);
            }
            if (mFfwdButton != null && !mCanSeekForward.getBoolean(mPlayer)) {
                mFfwdButton.setEnabled(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } catch (IncompatibleClassChangeError ex) {
            // We were given an old version of the interface, that doesn't have
            // the canPause/canSeekXYZ methods. This is OK, it just means we
            // assume the media can be paused and seeked, and so we don't disable
            // the buttons.
        }
    }
    
    
    /**
     * Show the controller on screen. It will go away
     * automatically after 'timeout' milliseconds of inactivity.
     * @param timeout The timeout in milliseconds. Use 0 to show
     * the controller until hide() is called.
     */
    public void show(int timeout) {
        //super.show(timeout);
        if (!mShowing && mAnchor != null) {
            setProgress();
            if (mPauseButton != null) {
                mPauseButton.requestFocus();
            }
 
            disableUnsupportedButtons();

            int [] anchorpos = new int[2];
            mAnchor.getLocationOnScreen(anchorpos);

            WindowManager.LayoutParams p = new WindowManager.LayoutParams();
            p.gravity = Gravity.TOP;
            p.width = mAnchor.getWidth();
            p.height = LayoutParams.WRAP_CONTENT;
            p.x = 0;
            p.y = anchorpos[1] + mAnchor.getHeight() - p.height;
            p.format = PixelFormat.TRANSLUCENT;
            p.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
            p.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
            p.token = null;
            p.windowAnimations = 0;//android.R.style.DropDownAnimationDown;
            mWindowManager.addView(mDecor, p);
            mShowing = true;
        }
        updatePausePlay();
        //setBatteryLevel();
        setNetwork();
        setCurrentTime();  
        
        // cause the progress bar to be updated even if mShowing
        // was already true.  This happens, for example, if we're
        // paused with the progress bar showing the user hits play.
        mHandler.sendEmptyMessage(SHOW_PROGRESS);

        Message msg = mHandler.obtainMessage(FADE_OUT);
        if (timeout != 0) {
            mHandler.removeMessages(FADE_OUT);
            mHandler.sendMessageDelayed(msg, timeout);
        }
    }
    
    public boolean isShowing() {
        return mShowing;
    }

    /**
     * Remove the controller from the screen.
     */
    public void hide() {
        if (mAnchor == null)
            return;

        if (mShowing) {
            try {
                mHandler.removeMessages(SHOW_PROGRESS);
                mWindowManager.removeView(mDecor);
            } catch (IllegalArgumentException ex) {
                Logger.w("MyMediaController", "already removed");
            }
            mShowing = false;
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int pos;
            switch (msg.what) {
                case FADE_OUT:
                    hide();
                    break;
                case SHOW_PROGRESS:
                    pos = setProgress();
                    if (!mDragging && mShowing && mPlayer.isPlaying()) {
                        msg = obtainMessage(SHOW_PROGRESS);
                        sendMessageDelayed(msg, 1000 - (pos % 1000));
                    }
                    break;
            }
        }
    };

    private String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours   = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    private int setProgress() {
        if (mPlayer == null || mDragging) {
            return 0;
        }
        int position = mPlayer.getCurrentPosition();
        int duration = mPlayer.getDuration();
        if (mProgress != null) {
            if (duration > 0) {
                // use long to avoid overflow
                long pos = 1000L * position / duration;
                mProgress.setProgress( (int) pos);
            }
            int percent = mPlayer.getBufferPercentage();
            mProgress.setSecondaryProgress(percent * 10);
        }

        if (mEndTime != null)
            mEndTime.setText(stringForTime(duration));
        if (mCurrentTime != null)
            mCurrentTime.setText(stringForTime(position));

        return position;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        show(sDefaultTimeout);
        return false;
    }

	@Override
    public boolean onTrackballEvent(MotionEvent ev) {
        show(sDefaultTimeout);
        return false;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int keyCode = event.getKeyCode();
        if (event.getRepeatCount() == 0  && (
                keyCode ==  KeyEvent.KEYCODE_HEADSETHOOK ||
                keyCode ==  KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE ||
                keyCode ==  KeyEvent.KEYCODE_SPACE)) {
            doPauseResume();
            show(sDefaultTimeout);
            if (mPauseButton != null) {
                mPauseButton.requestFocus();
            }
            return true;
        } else if (keyCode ==  KeyEvent.KEYCODE_MEDIA_STOP) {
            if (mPlayer.isPlaying()) {
                mPlayer.pause();
                updatePausePlay();
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
                keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            // don't show the controls for volume adjustment
        	if(event.getAction() == KeyEvent.ACTION_UP) {
        		showVolumnSeekBar(View.VISIBLE);
            	if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
                	mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, 0);
                else mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0);
                show(sDefaultTimeout);
                setVolume();
        	}

            return super.dispatchKeyEvent(event);
        } else if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) {
            hide();

            return true;
        } else {
            show(sDefaultTimeout);
        }
        return super.dispatchKeyEvent(event);
    }
       
    /**
     * 显示或隐藏剧集列表 
    */
    private void showEpisodeList() {
    	if(mEpisodeSrollView.getVisibility() == View.VISIBLE) mEpisodeSrollView.setVisibility(View.GONE);
    	else {
    		mEpisodeSrollView.setVisibility(View.VISIBLE);
    	}
    }
    
    /**
     * 剧集列表按钮监听
    */
    private View.OnClickListener mEpisodeListener = new View.OnClickListener() {
        public void onClick(View v) {
        	showEpisodeList();
        	show(sDefaultTimeout);
        }
    };
    
    /**
     * 剧集列表按钮点击响应
    */
    private View.OnClickListener mEpisodeListListener = new View.OnClickListener() {
        public void onClick(View v) {
        	int index = Integer.parseInt(v.getTag().toString());
        	onEpisodeItemClick(index);
        	setVideoTitle(mTitleText, index);
        	mTitle.setText(mTitleText+" "+getEpisodeText(index));
        }
    };
    
	private OnEpisodeItemClickListener mOnEpisodeItemClickListener;
    
	private void onEpisodeItemClick(int index) {
		if (mOnEpisodeItemClickListener != null) {
			mOnEpisodeItemClickListener.onClick(index);
		}
	}

	public interface OnEpisodeItemClickListener {
		void onClick(int index);
	}

	public void setOnEpisodeItemClickListener(OnEpisodeItemClickListener listener) {
		mOnEpisodeItemClickListener = listener;
	}
    
    /**
     * 设置音量seekbar的值
     */
	private void setVolume() {
    	mVolumeSeekBar.setProgress(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
    }

    /**
     * 显示或隐藏音量seekbar
     */
	private final static int NON_VISIBILITY = -100;
    private void showVolumnSeekBar(int visibility) {
    	if(visibility == NON_VISIBILITY) {
    		//根据seekbar的状态显示
        	if(mVolumeSeekBar.getVisibility() == View.VISIBLE) mVolumeSeekBar.setVisibility(View.GONE);
        	else {
        		setVolume();
        		mVolumeSeekBar.setVisibility(View.VISIBLE);
        	}
    	} else {
    		mVolumeSeekBar.setVisibility(visibility);
    	}

    }

    /**
     * 显示或隐藏音量seekbar监听
     */
    private View.OnClickListener mVolumnListener = new View.OnClickListener() {
        public void onClick(View v) {
        	showVolumnSeekBar(NON_VISIBILITY);
        	show(sDefaultTimeout);
        }
    };
    
    /**
     * 音量seekbar拖动监听
     */
    private VerticalSeekBar.OnSeekBarChangeListener mVolumeSeekListener = new VerticalSeekBar.OnSeekBarChangeListener() {

		@Override
		public void onProgressChanged(VerticalSeekBar VerticalSeekBar,
				int progress, boolean fromUser) {
			// TODO Auto-generated method stub
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
		}

		@Override
		public void onStartTrackingTouch(VerticalSeekBar VerticalSeekBar) {
			// TODO Auto-generated method stub
			show(3600000);
		}

		@Override
		public void onStopTrackingTouch(VerticalSeekBar VerticalSeekBar) {
			// TODO Auto-generated method stub
			show(sDefaultTimeout);
		}
    	
    };
    
    /**
     * 初始化亮度seekbar的值
     */
    private void setInitBright() {
    	int bright = SystemUtils.getScreenBrightness((Activity)mContext);
    	try {
			SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(mContext);   
			bright = preference.getInt(BRIGHT_TAG, SystemUtils.getScreenBrightness((Activity)mContext));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mBrightSeekBar.setProgress(bright);
		setScreenBrightness((float)bright/255);
    }
    
    /**
     * 设置屏幕亮度
     */
    private void setScreenBrightness(float b){  
    	if(b <= 0.1f) b = 0.1f;
        //取得window属性保存在layoutParams中  
    	Window window = ((Activity)mContext).getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();  
        layoutParams.screenBrightness = b; 
        window.setAttributes(layoutParams);  
        //显示修改后的亮度  
        layoutParams = window.getAttributes();   
    } 
    
    /**
     * 显示亮度seekbar
     */
    private void showBrightSeekBar() {
    	if(mBrightSeekBar.getVisibility() == View.VISIBLE) mBrightSeekBar.setVisibility(View.GONE);
    	else {
    		//setInitBright();
    		mBrightSeekBar.setVisibility(View.VISIBLE);
    	}
    }
    
    /**
     * 显示或隐藏亮度seekbar监听
     */
    private View.OnClickListener mBrightListener = new View.OnClickListener() {
        public void onClick(View v) {
        	showBrightSeekBar();
        	show(sDefaultTimeout);
        }
    };
    
    /**
     * 亮度seekbar拖动监听
     */
    private VerticalSeekBar.OnSeekBarChangeListener mBrightSeekListener = new VerticalSeekBar.OnSeekBarChangeListener() {
        private int mProgress = 0;
    	
		@Override
		public void onProgressChanged(VerticalSeekBar VerticalSeekBar,
				int progress, boolean fromUser) {
			// TODO Auto-generated method stub
			setScreenBrightness((float)progress/255);
			mProgress = progress;
		}

		@Override
		public void onStartTrackingTouch(VerticalSeekBar VerticalSeekBar) {
			// TODO Auto-generated method stub
			show(3600000);
		}

		@Override
		public void onStopTrackingTouch(VerticalSeekBar VerticalSeekBar) {
			// TODO Auto-generated method stub
			SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(mContext);   
			preference.edit().putInt(BRIGHT_TAG, mProgress).commit();
			show(sDefaultTimeout);
		}
    	
    };
    
    private View.OnClickListener mPauseListener = new View.OnClickListener() {
        public void onClick(View v) {
            doPauseResume();
            show(sDefaultTimeout);
        }
    };

    private void updatePausePlay() {
        if (mRoot == null || mPauseButton == null)
            return;

        if (mPlayer.isPlaying()) {
            mPauseButton.setImageResource(android.R.drawable.ic_media_pause);
        } else {
            mPauseButton.setImageResource(android.R.drawable.ic_media_play);
        }
    }

    private void doPauseResume() {
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
        } else {
            mPlayer.start();
        }
        updatePausePlay();
    }

    // There are two scenarios that can trigger the seekbar listener to trigger:
    //
    // The first is the user using the touchpad to adjust the posititon of the
    // seekbar's thumb. In this case onStartTrackingTouch is called followed by
    // a number of onProgressChanged notifications, concluded by onStopTrackingTouch.
    // We're setting the field "mDragging" to true for the duration of the dragging
    // session to avoid jumps in the position in case of ongoing playback.
    //
    // The second scenario involves the user operating the scroll ball, in this
    // case there WON'T BE onStartTrackingTouch/onStopTrackingTouch notifications,
    // we will simply apply the updated position without suspending regular updates.
    private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
        public void onStartTrackingTouch(SeekBar bar) {
            show(3600000);

            mDragging = true;

            // By removing these pending progress messages we make sure
            // that a) we won't update the progress while the user adjusts
            // the seekbar and b) once the user is done dragging the thumb
            // we will post one of these messages to the queue again and
            // this ensures that there will be exactly one message queued up.
            mHandler.removeMessages(SHOW_PROGRESS);
        }

        public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
            if (!fromuser) {
                // We're not interested in programmatically generated changes to
                // the progress bar's position.
                return;
            }

            long duration = mPlayer.getDuration();
            long newposition = (duration * progress) / 1000L;
            mPlayer.seekTo( (int) newposition);
            if (mCurrentTime != null)
                mCurrentTime.setText(stringForTime( (int) newposition));
        }

        public void onStopTrackingTouch(SeekBar bar) {
            mDragging = false;
            setProgress();
            updatePausePlay();
            show(sDefaultTimeout);

            // Ensure that progress is properly updated in the future,
            // the call to show() does not guarantee this because it is a
            // no-op if we are already showing.
            mHandler.sendEmptyMessage(SHOW_PROGRESS);
        }
    };

    @Override
    public void setEnabled(boolean enabled) {
        if (mPauseButton != null) {
            mPauseButton.setEnabled(enabled);
        }
        if (mFfwdButton != null) {
            mFfwdButton.setEnabled(enabled);
        }
        if (mRewButton != null) {
            mRewButton.setEnabled(enabled);
        }
        if (mNextButton != null) {
            mNextButton.setEnabled(enabled && mNextListener != null);
        }
        if (mPrevButton != null) {
            mPrevButton.setEnabled(enabled && mPrevListener != null);
        }
        if (mProgress != null) {
            mProgress.setEnabled(enabled);
        }
        disableUnsupportedButtons();
        super.setEnabled(enabled);
    }
    
    private View.OnClickListener mRewListener = new View.OnClickListener() {
        public void onClick(View v) {
            int pos = mPlayer.getCurrentPosition();
            pos -= 5000; // milliseconds
            mPlayer.seekTo(pos);
            setProgress();

            show(sDefaultTimeout);
        }
    };

    private View.OnClickListener mFfwdListener = new View.OnClickListener() {
        public void onClick(View v) {
            int pos = mPlayer.getCurrentPosition();
            pos += 15000; // milliseconds
            mPlayer.seekTo(pos);
            setProgress();

            show(sDefaultTimeout);
        }
    };

    private void installPrevNextListeners() {
        if (mNextButton != null) {
            mNextButton.setOnClickListener(mNextListener);
            mNextButton.setEnabled(mNextListener != null);
        }

        if (mPrevButton != null) {
            mPrevButton.setOnClickListener(mPrevListener);
            mPrevButton.setEnabled(mPrevListener != null);
        }
    }

    public void setPrevNextListeners(View.OnClickListener next, View.OnClickListener prev) {
        mNextListener = next;
        mPrevListener = prev;
        mListenersSet = true;

        if (mRoot != null) {
            installPrevNextListeners();
            
            if (mNextButton != null && !mFromXml) {
                mNextButton.setVisibility(View.VISIBLE);
            }
            if (mPrevButton != null && !mFromXml) {
                mPrevButton.setVisibility(View.VISIBLE);
            }
        }
    }

}
